package com.kun.flutter_app

import android.content.Context
import android.util.Log
import android.view.View
import android.widget.TextView
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.platform.PlatformView

/**
 * @author: liangkun
 * @date: 2021/4/21 13:46
 * @description:创建android---view
 * messenger 用于消息传递，后面介绍 Flutter 与 原生通信时用到此参数。
 * viewId--------------View 生成时会分配一个唯一 ID
 * args：Flutter 传递的初始化参数
 */
class FlutterView(context: Context, messenger: BinaryMessenger, viewId: Int, args: Map<String, Any>?) : PlatformView, MethodChannel.MethodCallHandler {
    private val textView = TextView(context)
    private var methodChannel: MethodChannel

    init {
        //构造方法
        textView.text = args?.get("text") as String
        //flutter传递参数给android原生
        methodChannel = MethodChannel(messenger, "com.flutter.to.android$viewId")
        methodChannel.setMethodCallHandler(this)
    }

    override fun getView(): View {
        //返回android的view
        return textView
    }

    override fun dispose() {
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        if (call.method == "setText") {
            //给原生view设置数据
            val name = call.argument("name") as String?
            val age = call.argument("age") as Int?

            textView.text = String.format("hello,姓名：%s,年龄：%s", name, age)
        } else if (call.method == "getData") {
            //向原生android获取数据
            val name = call.argument("name") as String?
            val age = call.argument("age") as Int?

            var map = mapOf("name" to "hello,$name",
                    "age" to "$age"
            )
            result.success(map)
        } else {
            result.notImplemented()
        }
    }
}